package com.xgh.offer;

import com.xgh.ListNode;

/**
 * @ClassName Offer25
 * @Description
 * @Author xinggh
 * @Date 2020/6/30 23:12
 * @Version 1.0
 **/
public class Offer25 {
    /**
     * 剑指 Offer 25. 合并两个排序的链表
     * 输入两个递增排序的链表，合并这两个链表并使新链表中的节点仍然是递增排序的。
     * <p>
     * 示例1：
     * <p>
     * 输入：1->2->4, 1->3->4
     * 输出：1->1->2->3->4->4
     * 限制：
     * <p>
     * 0 <= 链表长度 <= 1000
     */
    public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {

      /*  if (l1 == null) {
            return l2;
        }
        if (l2 == null) {
            return l1;
        }
        ListNode h1 = l1;
        ListNode h2 = l2;
        ListNode hnew = null;
        if (h1.val < h2.val) {
            hnew = h1;
            h1 = h1.next;
        } else {
            hnew = h2;
            h2 = h2.next;
        }
        ListNode curr = hnew;
        while (h1 != null && h2 != null) {
            if (h1.val < h2.val) {
                curr.next = h1;
                curr = h1;
                h1 = h1.next;
            } else {
                curr.next = h2;
                curr = h2;
                h2 = h2.next;
            }
        }

        if (h1 == null) {
            curr.next = h2;
        } else {
            curr.next = h1;
        }
        return hnew;*/
            ListNode dum = new ListNode(0), cur = dum;

            while (l1 != null && l2 != null) {
                if (l1.val < l2.val) {
                    cur.next = l1;
                    l1 = l1.next;
                } else {
                    cur.next = l2;
                    l2 = l2.next;
                }
                cur = cur.next;
            }

            cur.next = (l1 == null) ? l2 : l1;
            return dum.next;
    }


    public static void main(String[] args) {
        ListNode l1 = new ListNode(1);
        ListNode l2 = new ListNode(2);
        ListNode l3 = new ListNode(4);
        l1.next = l2;
        l2.next = l3;

        ListNode ll1 = new ListNode(1);
        ListNode ll2 = new ListNode(3);
        ListNode ll3 = new ListNode(4);
        ll1.next = ll2;
        ll2.next = ll3;
        mergeTwoLists(l1, ll1);

    }
}
